package com.rzjm.exercise.module.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rzjm.exercise.common.base.controller.BaseController;
import com.rzjm.exercise.common.base.data.DataTableLayUI;
import com.rzjm.exercise.common.log.annotation.Log;
import com.rzjm.exercise.common.utils.*;
import com.rzjm.exercise.module.domain.*;
import com.rzjm.exercise.module.service.ShopService;
import com.rzjm.exercise.module.service.TempProjectRecordService;
import com.rzjm.exercise.module.service.TempProjectService;
import com.rzjm.exercise.module.service.TempProjectUserService;
import com.rzjm.exercise.sys.core.dict.annotation.DictBody;
import com.rzjm.exercise.sys.system.user.domain.UserDO;
import com.rzjm.exercise.sys.system.user.service.UserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.*;

/**
 * 临时项目
 *
 * @author mr.zhou
 * @email zhouwei_nice@163.com
 * @date 2018-12-15 22:20:07
 */

@Controller
@RequestMapping("/module/tempro")
public class TempProjectController extends BaseController {
    @Resource
    private TempProjectService tempProjectService;
    @Resource
    private TempProjectUserService tempProjectUserService;
    @Resource
    private TempProjectRecordService tempProjectRecordService;
    @Resource
    private UserService userService;
    @Resource
    private ShopService shopService;

    @Value("${projecturl.imgurl}")
    private String imgUrl;
    @Value("${projecturl.uploadPath}")
    private String uploadPath;


    @Log("查询临时项目页面")
    @GetMapping()
    @RequiresPermissions("module:tempro:tempro")
    String TempProject() {
        return "module/tempro/tempro";
    }


    @Log("查询临时项目页面")
    @GetMapping("/record")
    @RequiresPermissions("module:tempro:tempro")
    String TempProjectRecord(Model model) {
        UserDO user = getUser();
        List<Shop> shops = new ArrayList<>();
        if(user.getUserType() == 0 || user.getUserType() == 1){//平台管理员可以查看所有的
            shops = shopService.selectAllList();
        } else if(user.getUserType() == 2 ){//集团管理员可以查看自己所管辖的
            Map<String,Object> map = new HashMap<>();
            map.put("jituan_user_id",user.getUserId());
            shops = shopService.getPageByUserId(map);
        } else if(user.getUserType() == 3){//片区管理员可以查看自己所管辖的
            Map<String,Object> map = new HashMap<>();
            map.put("sys_user_id",user.getUserId());
            shops = shopService.getPageByUserId(map);
        } else if(user.getUserType() == 4 || user.getUserType() == 5 || user.getUserType() == 6){//分厂和巡检人员只能查看自己绑定的那个一个
            Map<String,Object> map = new HashMap<>();
            map.put("id",user.getShopId());
            shops = shopService.getPageByUserId(map);
        }
        model.addAttribute("shops", shops);
        return "module/tempro/record";
    }

    @Log("查询临时项目页面")
    @GetMapping("/user")
    @RequiresPermissions("module:tempro:user")
    String TempProjectUser() {
        return "module/tempro/user";
    }

    @Log("查询临时项目")
    @ResponseBody
    @DictBody
    @GetMapping("/list")
    @RequiresPermissions("module:tempro:tempro")
    public DataTableLayUI<TempProject> list(DataTableLayUI<TempProject> condition) {
        UserDO user = getUser();
        Map<String,Object> map = condition.getSearchParams();
//        map.put("search_eq_shopId",user.getShopId());
        DataTableLayUI<TempProject> dt = tempProjectService.pageSearchLayUI(condition);
        List<TempProject> list = dt.getData();
        list.forEach(post->{
            if(StrUtil.isNotEmpty(post.getQrCode())){
                post.setQrCode(imgUrl + post.getQrCode());
            }
        });
        return dt;
    }


    @Log("查询临时项目")
    @ResponseBody
    @DictBody
    @GetMapping("/user/list")
    @RequiresPermissions("module:tempro:user")
    public DataTableLayUI<TempProjectUser> userList(DataTableLayUI<TempProjectUser> condition) {
        UserDO user = getUser();
        Map<String,Object> map = condition.getSearchParams();
//        map.put("search_eq_shopId",user.getShopId());
        DataTableLayUI<TempProjectUser> dt = tempProjectUserService.pageSearchLayUI(condition);
        return dt;
    }

    @Log("查询临时项目的上报记录")
    @ResponseBody
    @DictBody
    @GetMapping("/record/list")
    @RequiresPermissions("module:tempro:record")
    public DataTableLayUI<TempProjectRecord> recordList(DataTableLayUI<TempProjectRecord> condition) {
        UserDO user = getUser();
        Map<String,Object> map = condition.getSearchParams();
        String shopId = map.containsKey("search_eq_shopId") ? map.get("search_eq_shopId").toString():null;
        String begin_time = map.containsKey("search_ge_createTime") ? map.get("search_ge_createTime").toString():null;
        String end_time = map.containsKey("search_le_createTime") ? map.get("search_le_createTime").toString():null;

        Map<String,Object> map1 = new HashMap<>();
        if(user.getUserType() == 0 || user.getUserType() == 1){
            if(StrUtil.isNotEmpty(shopId)){
                map1.put("shop_id",Integer.parseInt(shopId));
            }
        } else if(user.getUserType() == 2){//集团管理员
            if(StrUtil.isNotEmpty(shopId)){
                map1.put("shop_id",Integer.parseInt(shopId));
            }else{
                map1.put("jituan_user_id",user.getUserId());
            }
        }else if(user.getUserType() == 3){//片区管理员
            if(StrUtil.isNotEmpty(shopId)){
                map1.put("shop_id",Integer.parseInt(shopId));
            }else{
                map1.put("sys_user_id",user.getUserId());
            }
        } else if(user.getUserType() == 4 || user.getUserType() == 5 || user.getUserType() == 6){//巡检人员  分厂管理人员
            if(StrUtil.isNotEmpty(shopId)){
                map1.put("shop_id",Integer.parseInt(shopId));
            }else{
                map1.put("shop_id",user.getShopId());
            }
        }
        if(begin_time!=null && end_time!=null){
            map1.put("begin_time",begin_time);
            map1.put("end_time",end_time);
        }
        Page<TempProjectRecord> page = tempProjectRecordService.getPage(condition);
        List<TempProjectRecord> list = tempProjectRecordService.getPageByUserId(page,map1);
        DataTableLayUI<TempProjectRecord> dt = tempProjectRecordService.pageSearchCustom(page,list,condition);
        if(list != null) {
            list.forEach(record -> {
                List<String> imgsList = new ArrayList<>();
                if(StrUtil.isNotEmpty(record.getImgs())){
                    String[] imgArray = record.getImgs().split(",");
                    for(String img : imgArray){
                        img = imgUrl + img;
                        imgsList.add(img);
                    }
                    record.setImgUrls(imgsList);
                }
            });
        }
        return dt;
    }

    @Log("新增企业页面")
    @GetMapping("/add")
    @RequiresPermissions("module:tempro:add")
    String add(Model model) {
        UserDO user = getUser();
        TempProject tempProject = new TempProject();
        List<Shop> shops = new ArrayList<>();
        if(user.getUserType() == 0 || user.getUserType() == 1){//平台管理员可以查看所有的
            shops = shopService.selectAllList();
        } else if(user.getUserType() == 2 ){//集团管理员可以查看自己所管辖的
            Map<String,Object> map = new HashMap<>();
            map.put("jituan_user_id",user.getUserId());
            shops = shopService.getPageByUserId(map);
        } else if(user.getUserType() == 3){//片区管理员可以查看自己所管辖的
            Map<String,Object> map = new HashMap<>();
            map.put("sys_user_id",user.getUserId());
            shops = shopService.getPageByUserId(map);
        } else if(user.getUserType() == 4 || user.getUserType() == 5 || user.getUserType() == 6){//分厂和巡检人员只能查看自己绑定的那个一个
            Map<String,Object> map = new HashMap<>();
            map.put("id",user.getShopId());
            shops = shopService.getPageByUserId(map);
        }
        model.addAttribute("shops", shops);
        model.addAttribute("temppro", tempProject);
        return "module/tempro/detail";
    }

    @Log("编辑临时项目页面")
    @GetMapping("/edit/{id}")
    @RequiresPermissions("module:tempro:edit")
    String edit(@PathVariable("id") Integer id, Model model) {
        TempProject tempProject = tempProjectService.getById(id);

        UserDO user = getUser();
        List<Shop> shops = new ArrayList<>();
        if(user.getUserType() == 0 || user.getUserType() == 1){//平台管理员可以查看所有的
            shops = shopService.selectAllList();
        } else if(user.getUserType() == 2 ){//集团管理员可以查看自己所管辖的
            Map<String,Object> map = new HashMap<>();
            map.put("jituan_user_id",user.getUserId());
            shops = shopService.getPageByUserId(map);
        } else if(user.getUserType() == 3){//片区管理员可以查看自己所管辖的
            Map<String,Object> map = new HashMap<>();
            map.put("sys_user_id",user.getUserId());
            shops = shopService.getPageByUserId(map);
        } else if(user.getUserType() == 4 || user.getUserType() == 5 || user.getUserType() == 6){//分厂和巡检人员只能查看自己绑定的那个一个
            Map<String,Object> map = new HashMap<>();
            map.put("id",user.getShopId());
            shops = shopService.getPageByUserId(map);
        }
        model.addAttribute("shops", shops);
        model.addAttribute("temppro", tempProject);
        return "module/tempro/detail";
    }

    @Log("导出列表")
    @GetMapping("/record/exportExcel")
    public void testExprotExcel(@RequestParam("begin_date") String begin_date, @RequestParam("end_date") String end_date,
                                @RequestParam("shopId") String shopId,HttpServletRequest request, HttpServletResponse response){
        UserDO user = getUser();
        Map<String,Object> map = new HashMap<>();
        if(user.getUserType() == 0 || user.getUserType() == 1){
            if(StrUtil.isNotEmpty(shopId)){
                map.put("shop_id",Integer.parseInt(shopId));
            }
        } else if(user.getUserType() == 2){//集团管理员
            if(StrUtil.isNotEmpty(shopId)){
                map.put("shop_id",Integer.parseInt(shopId));
            }else{
                map.put("jituan_user_id",user.getUserId());
            }
        }else if(user.getUserType() == 3){//片区管理员
            if(StrUtil.isNotEmpty(shopId)){
                map.put("shop_id",Integer.parseInt(shopId));
            }else{
                map.put("sys_user_id",user.getUserId());
            }
        }
        else if(user.getUserType() == 4 || user.getUserType() == 5 || user.getUserType() == 6){
            map.put("shop_id",user.getShopId());
        }

        if(StrUtil.isNotEmpty(begin_date) && StrUtil.isNotEmpty(end_date)){
            map.put("begin_time",begin_date +" 00:00:00");
            map.put("end_time",end_date +" 23:59:59");
        }
        List<TempProjectRecord> records = tempProjectRecordService.getPageByUserId(map);
        records.forEach(record->{
            record.setCreateTimeStr(DateUtils.getTime(record.getCreateTime()));
        });
        ExcelUtils.writeExcel(response, records, TempProjectRecord.class, System.currentTimeMillis() + "_临时项目上报记录.xlsx");
    }

    /**
     * 重置二维码
     */
    @Log("重置二维码")
    @PostMapping("/resetQrcode")
    @ResponseBody
    @RequiresPermissions("module:tempro:edit")
    public R resetQrcode( Integer id) {
        TempProject tempProject = tempProjectService.findById(id);
        if(tempProject!=null){
            try{
                String qrcode = "";
                String fileName = "tempro_qr_"+tempProject.getShopId() + "_" + tempProject.getProjectNum() +".jpg";
                String content = "{\"qrtype\":\"tempro\",\"shop_id\":"+tempProject.getShopId()+",\"num\":\""+tempProject.getProjectNum()+"\"}";
                Aes aes = new Aes();
                content = aes.encrypt(content);
                System.out.println("content:  "+ content);
                //上传头像到OSS
                String img_key = "";
                int upload_type = OssUtil.TYPE_TEMPRO_PHOTOS;
                img_key = OssUtil.getUploadPrefix(upload_type) + fileName;
                QRCodeUtilEx.createQrCodeImg(content, tempProject.getProjectNum() +"   NO. "+ tempProject.getProjectNum(), null, uploadPath +"/"+ img_key, true);
                qrcode = img_key;
                tempProject.setQrCode(qrcode);
            }catch (Exception ex){
                ex.printStackTrace();
            }
            if (tempProjectService.updateById(tempProject)) {
                return R.ok();
            }
        }
        return R.error();
    }

    /**
     * 下载岗位二维码
     */
    @Log("下载岗位二维码")
    @GetMapping("/download/{projectNum}")
    public void download(@PathVariable("projectNum") String projectNum, HttpServletResponse response) {
        TempProject tempProject = tempProjectService.selectByUniqueColumn("project_num",projectNum);
        if(tempProject!=null){
            FileUtils.download(uploadPath + tempProject.getQrCode(),response);
        }
    }

    /**
     * 保存
     */
    @Log("新增OA审批")
    @ResponseBody
    @PostMapping("/save")
    @RequiresPermissions("module:tempro:add")
    @Transactional
    public R save(@Valid TempProject tempProject) {
        UserDO user = getUser();
        tempProject.setCreateTime(new Date());
        Shop shop = shopService.findById(tempProject.getShopId());
        if(shop!=null){
            tempProject.setShopName(shop.getShopName());
        }
        //项目状态 0 - 未启用 1 - 已启用  2 - 已禁用 3 - 项目进行中  4 - 项目已结束
        boolean ret = tempProjectService.save(tempProject);
        if(ret){
            String pro_num = StringUtil.LeftBuCode(tempProject.getId().toString(),6);
            tempProject.setProjectNum(pro_num);
            try{
                String qrcode = "";
                String fileName = "tempro_qr_"+tempProject.getShopId() + "_" + tempProject.getProjectNum() +".jpg";
                String content = "{\"qrtype\":\"tempro\",\"shop_id\":"+tempProject.getShopId()+",\"num\":\""+tempProject.getProjectNum()+"\"}";
                Aes aes = new Aes();
                content = aes.encrypt(content);
                System.out.println("content:  "+ content);
                //上传头像到OSS
                String img_key = "";
                int upload_type = OssUtil.TYPE_TEMPRO_PHOTOS;
                img_key = OssUtil.getUploadPrefix(upload_type) + fileName;
                QRCodeUtilEx.createQrCodeImg(content, tempProject.getProjectNum() +"   NO. "+ tempProject.getProjectNum(), null, uploadPath +"/"+ img_key, true);
                qrcode = img_key;
                tempProject.setQrCode(qrcode);
            }catch (Exception ex){
                ex.printStackTrace();
            }
            ret = tempProjectService.updateById(tempProject);
            if(ret){
                return R.ok();
            }
        }
        return R.error();
    }

    /**
     * 修改
     */
    @Log("更新临时项目")
    @ResponseBody
    @RequestMapping("/update")
    @RequiresPermissions("module:tempro:edit")
    public R update(@Valid TempProject tempProject) {
        if(StrUtil.isEmpty(tempProject.getShopName())){
            Shop shop = shopService.findById(tempProject.getShopId());
            if(shop!=null){
                tempProject.setShopName(shop.getShopName());
            }
        }
        if(StrUtil.isEmpty(tempProject.getProjectNum())){
            String pro_num = StringUtil.LeftBuCode(tempProject.getId().toString(),6);
            tempProject.setProjectNum(pro_num);
            try{
                String qrcode = "";
                String fileName = "tempro_qr_"+tempProject.getShopId() + "_" + tempProject.getProjectNum() +".jpg";
                String content = "{\"qrtype\":\"tempro\",\"shop_id\":"+tempProject.getShopId()+",\"num\":\""+tempProject.getProjectNum()+"\"}";
                Aes aes = new Aes();
                content = aes.encrypt(content);
                System.out.println("content:  "+ content);
                //上传头像到OSS
                String img_key = "";
                int upload_type = OssUtil.TYPE_TEMPRO_PHOTOS;
                img_key = OssUtil.getUploadPrefix(upload_type) + fileName;
                QRCodeUtilEx.createQrCodeImg(content, tempProject.getProjectNum() +"   NO. "+ tempProject.getProjectNum(), null, uploadPath +"/"+ img_key, true);
                qrcode = img_key;
                tempProject.setQrCode(qrcode);
            }catch (Exception ex){
                ex.printStackTrace();
            }
        }
        tempProjectService.updateById(tempProject);
        return R.ok();
    }

    /**
     * 删除
     */
    @Log("删除临时项目")
    @PostMapping("/remove")
    @ResponseBody
    @RequiresPermissions("module:tempro:remove")
    @Transactional
    public R remove( Integer id) {
        try{
            if (tempProjectService.removeById(id)) {
                return R.ok();
            }
        }catch (Exception e){

        }
        return R.error();
    }
}
